import React, { useState } from 'react';
import  'antd/dist/antd.css'
import {Card, Input, Icon,Button ,Spin,message} from 'antd'
import  '../static/css/Login.css'
import axios from 'axios'
import servicePath from '../config/apiUrl'
function Login(props) {
    const [userName,setUserName ]=useState('')
    const [password ,setPassword ]=useState('')
    const [isLoading,setIsLoading ]=useState(false)
    const checkLogin=()=>{
        // 变化时候就已经重新赋值username 和password
        console.log(11111111111)
        setIsLoading(true)//出现loading
        if(!userName){
            message.error('用户名不能为空')
            setTimeout(() => {
                setIsLoading(false)
            }, 1000);
            return false
        }else if(!password){
            message.error('密码不能为空')
            setTimeout(() => {
                setIsLoading(false)
            }, 1000);
            return false
        }
        let dataProps = {
            'userName':userName,
            'password':password
        }

        axios({
            method:'post',
            url:servicePath.checkLogin,
            data:dataProps,//参数
            withCredentials:true//前端后端共享session
        }).then(res=>{
            setIsLoading(false)//消失，为true 防止重复提交多次请求
            // 返回一个对象 this.ctx.body={'data':'登录成功','openId':openId}
            if (res.data.data==='登录成功') {
                localStorage.setItem('openId',res.data.openId)
                // 编程导航跳转到首页
                console.log(props)
                props.history.push('/index')
            }else{
                message.error('用户名密码错误')
            }
        })
        
        setTimeout(() => {
            setIsLoading(false)   
        }, 1000);
    }
    return (
        <div className='login-div'>
          <Spin tip="Loading..." spinning={isLoading}>
              <Card title="JSPang Blog  System" bordered={true} style={{ width: 400 }}>
              <Input
                        id="userName"
                        size="large"
                        value={userName}
                        placeholder="Enter your userName"
                        prefix={<Icon type="user" style={{color:'rgba(0,0,0,.25)'}} />}
                        onChange={(e)=>{setUserName(e.target.value)}}
                    /> 
                    <br/><br/>
                    <Input.Password
                        id="password"
                        size="large"
                        value={password}
                        placeholder="Enter your password"
                        prefix={<Icon type="key" style={{color:'rgba(0,0,0,.25)'}} />}
                        onChange={(e)=>{setPassword(e.target.value)}}
                    />     
                    <br/><br/>
                    <Button type="primary" size="large" block onClick={checkLogin} > Login in </Button>
              </Card>
          </Spin>

        </div>
    )


}


export default Login